package io.terminus.lego.shinda.web.security.endpoint

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.terminus.lego.shinda.web.cache.RedisCacheManager
import io.terminus.lego.shinda.web.cache.RedisKeyConstant
import io.terminus.lego.shinda.web.security.dto.Response
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.util.concurrent.ThreadLocalRandom
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Endpoint-登录相关
 * @author wangmeng
 * @date 2018/4/12
 */
@Api(value = "Endpoint-登录相关")
@RestController
@RequestMapping("/api/login")
class LoginEndpoint @Autowired constructor(val redisCacheManager: RedisCacheManager) {

    val log = LoggerFactory.getLogger(javaClass)

    @ApiOperation("用户未登录内部转发地址")
    @GetMapping
    fun login(response: HttpServletResponse): Response {
        response.setHeader("Access-Control-Allow-Origin", "*")
        response.status = HttpStatus.UNAUTHORIZED.value()
        return Response(false, "user not login")
    }

    @ApiOperation("用户登录成功内部转发地址")
    @RequestMapping("success")
    fun success(request: HttpServletRequest): Response {
        val redirectUrl = request.getAttribute("redirectUrl")
        return Response(true, "login success", redirectUrl?.toString())
    }

    @ApiOperation("用户登录失败内部转发地址")
    @RequestMapping("failure")
    fun failure(request: HttpServletRequest): Response {
        return Response(false, request.getAttribute("error") as String)
    }

    @ApiOperation("短信验证码登录发送手机短信接口")
    @PostMapping("/phone/sms")
    fun sendSms(phone: String): Response {
        //TODO 实际上是调用消息中心的短信发送接口、目前是MOCK
        val nextInt = ThreadLocalRandom.current().nextInt()
        redisCacheManager.setValue(RedisKeyConstant.getPhoneLoginCodeKey(phone), "$nextInt", RedisKeyConstant.getSmsExpireTime())
        redisCacheManager.setValue(RedisKeyConstant.getPhoneLoginRetryKey(phone), 0, RedisKeyConstant.getSmsExpireTime())
        log.info("$phone 登录验证码：$nextInt")
        return Response(true, "$nextInt")
    }

    @ApiOperation("邮箱验证码登录发送邮箱验证码接口")
    @PostMapping("/email/code")
    fun sendEmailCode(email: String): Response {
        //TODO 实际上是调用消息中心的邮件发送接口、目前是MOCK
        val nextInt = ThreadLocalRandom.current().nextInt()
        redisCacheManager.setValue(RedisKeyConstant.getEmaiLoginCodelKey(email), "$nextInt", RedisKeyConstant.getSmsExpireTime())
        redisCacheManager.setValue(RedisKeyConstant.getEmailLoginRetryKey(email), 0, RedisKeyConstant.getSmsExpireTime())
        log.info("$email 登录验证码：$nextInt")
        return Response(true, "$nextInt")
    }

}